package com.tjec.project.businessStandardLibrary.service.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.tjec.common.constant.AttachmentConstants;
import com.tjec.common.enums.CodeNum;
import com.tjec.common.enums.NumCode;
import com.tjec.common.utils.DateUtils;
import com.tjec.common.utils.ServletUtils;
import com.tjec.common.utils.StringUtils;
import com.tjec.framework.security.service.TokenService;
import com.tjec.project.businessStandardLibrary.domain.BmsKnowledgeCase;
import com.tjec.project.system.domain.BmsAttachment;
import com.tjec.project.system.domain.BmsCategoryAssociated;
import com.tjec.project.system.domain.BmsMdBusinessCategory;
import com.tjec.project.system.mapper.BmsAttachmentMapper;
import com.tjec.project.system.mapper.BmsCategoryAssociatedMapper;
import com.tjec.project.system.mapper.BmsMdBusinessCategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tjec.project.businessStandardLibrary.mapper.BmsKnowledgeTemplateMapper;
import com.tjec.project.businessStandardLibrary.domain.BmsKnowledgeBusinessGuide;
import com.tjec.project.businessStandardLibrary.domain.BmsKnowledgeTemplate;
import com.tjec.project.businessStandardLibrary.service.IBmsKnowledgeTemplateService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 模板下载Service业务层处理
 * 
 * @author pangyognfeng
 * @date 2020-04-21
 */
@Service
public class BmsKnowledgeTemplateServiceImpl implements IBmsKnowledgeTemplateService 
{
    @Autowired
    private BmsKnowledgeTemplateMapper bmsKnowledgeTemplateMapper;
    @Autowired
    private BmsMdBusinessCategoryMapper bmsMdBusinessCategoryMapper;
    @Autowired
    private BmsAttachmentMapper bmsAttachmentMapper;
    @Autowired
    private BmsCategoryAssociatedMapper bmsCategoryAssociatedMapper;

    @Autowired
    private TokenService tokenService;
    /**
     * 查询模板下载
     * 
     * @param guid 模板下载ID
     * @return 模板下载
     */
    @Override
    public BmsKnowledgeTemplate selectBmsKnowledgeTemplateByGuid(String guid)
    {
        return bmsKnowledgeTemplateMapper.selectBmsKnowledgeTemplateByGuid(guid);
    }
    /**
     * 查询模板下载 详情
     *
     * @param guid 模板下载ID
     * @return 模板下载
     */
    @Override
    public BmsKnowledgeTemplate selectBmsKnowledgeTemplateByGuiddetails(String guid)
    {

        BmsKnowledgeTemplate bmsKnowledgeTemplate =bmsKnowledgeTemplateMapper.selectBmsKnowledgeTemplateByGuiddetails(guid);
        List<BmsMdBusinessCategory> bms = bmsKnowledgeTemplate.getBusinessCategorys();
        List<String> lists=new ArrayList<String>();
        for (BmsMdBusinessCategory bmsMdBusinessCategory:bms) {
            lists.add(bmsMdBusinessCategory.getGuid()) ;
        }
        bmsKnowledgeTemplate.setBusinessCategoryGuids(lists);
        return bmsKnowledgeTemplate;
    }

    /**
     * 查询模板下载列表
     * 
     * @param bmsKnowledgeTemplate 模板下载
     * @return 模板下载
     */
    @Override
    public List<BmsKnowledgeTemplate> selectBmsKnowledgeTemplateList(BmsKnowledgeTemplate bmsKnowledgeTemplate)
    {
    	
    	List<BmsKnowledgeTemplate> lists = bmsKnowledgeTemplateMapper.selectBmsKnowledgeTemplateList(bmsKnowledgeTemplate);
    	for(BmsKnowledgeTemplate list : lists) {
    		list.setContentSize(getFileSize(list.getContentLength()));
    	}
        return lists;
    }
    /**
     * 常用表单列表  改进
     * villwang
     * @param bmsKnowledgeTemplate 模板下载
     * @return 模板下载
     */
    @Override
    public List<BmsKnowledgeTemplate> selectBmsKnowledgeTemplateTreeList(BmsKnowledgeTemplate bmsKnowledgeTemplate) {

        String businessCategoryId=bmsKnowledgeTemplate.getBusinessCategoryId();
        List<String> ids=new ArrayList<>();
        List<BmsKnowledgeTemplate> bms=new ArrayList<>();
        //业务树查询
        if(StringUtils.isNotBlank(businessCategoryId)){
            int level = businessLevel(businessCategoryId);

            if(level== CodeNum.ONE.getCode()){
                ids= bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryChildIdsOne(businessCategoryId);
            }else if(level==CodeNum.TWO.getCode()){
                ids= bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryChildIdsTwo(businessCategoryId);
            }else {
                ids.add(businessCategoryId);
            }
            //没有第三层的问题
            if(ids.isEmpty()){
                ids.add(businessCategoryId);
            }
            bmsKnowledgeTemplate.setGuids(ids);
            bms=bmsKnowledgeTemplateMapper.selectBmsKnowledgeTemplateTreeList(bmsKnowledgeTemplate);
        }else {
            //不点业务树查询
            bms=bmsKnowledgeTemplateMapper.selectBmsKnowledgeTemplateTreeList(bmsKnowledgeTemplate);

        }
        
        if(ids.size()==1) {
       	 bms = bmsKnowledgeTemplateList(bms,businessCategoryId);
       }else {
       	 bms = bmsKnowledgeTemplateList(bms);
       }
        
        return bms;
    }
    
    /**
    *
    *@describe 组装数据
    *@params [bms]
    *@return java.util.List<com.tjec.project.businessStandardLibrary.domain.BmsKnowledgeTemplate>
    *@author VillWang
    *@date 2020/6/16
    *@other
    *
    */
   public List<BmsKnowledgeTemplate> bmsKnowledgeTemplateList(List<BmsKnowledgeTemplate> bms) {
       for (BmsKnowledgeTemplate bkc:bms) {
            String guid= bkc.getGuid();
           List<BmsMdBusinessCategory> bmsMdBusinessCategories = bmsMdBusinessCategoryMapper.selectBusinessCategoryByCategoryAssociatedId(guid);
           bkc.setBusinessCategorys(bmsMdBusinessCategories);
       }

       return bms;

   }
   
   /**
   *
   *@describe 组装数据
   *@params [bms]
   *@return java.util.List<com.tjec.project.businessStandardLibrary.domain.BmsKnowledgeTemplate>
   *@author VillWang
   *@date 2020/6/16
   *@other
   *
   */
  public List<BmsKnowledgeTemplate> bmsKnowledgeTemplateList(List<BmsKnowledgeTemplate> bms,String businessCategoryId) {
      for (BmsKnowledgeTemplate bkc:bms) {
           String guid= bkc.getGuid();
          BmsMdBusinessCategory bmsMdBusinessCategory = bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryByGuId(businessCategoryId);
          List<BmsMdBusinessCategory> bmsMdBusinessCategories = new ArrayList<BmsMdBusinessCategory>();
          bmsMdBusinessCategories.add(bmsMdBusinessCategory);
          bkc.setBusinessCategorys(bmsMdBusinessCategories);
      }

      return bms;

  }
  
    /**
     *
     *@describe   获取业务类别的层级
     *@params [businessCategoryId]
     *@return java.lang.String
     *@author VillWang
     *@date 2020/4/27
     *@other
     *
     */
    public int businessLevel(String businessCategoryId) {
        BmsMdBusinessCategory bms=  bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryByGuId(businessCategoryId);
        String parentId= bms.getParentId();
        //获取下级定位是否只有2层的问题
        BmsMdBusinessCategory bmsMdBusinessCategorynew = new BmsMdBusinessCategory();
        bmsMdBusinessCategorynew.setParentId(businessCategoryId);
        List<BmsMdBusinessCategory> bmsCategory= bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryList(bmsMdBusinessCategorynew);
        int flag=0;
        if(bmsCategory==null||bmsCategory.isEmpty()||bmsCategory.equals("")){
            //处理没有二级  和三级的  一级菜单

            return CodeNum.THREE.getCode();
        }else {
            for (BmsMdBusinessCategory bms2 : bmsCategory) {

                bmsMdBusinessCategorynew.setParentId(bms2.getGuid());
                List<BmsMdBusinessCategory> bmsCategory3= bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryList(bmsMdBusinessCategorynew);
                for (BmsMdBusinessCategory bms3:bmsCategory3) {
                    if(bms3==null||bms3.equals("")){
                    }else {
                        //标记是否有第三级
                        flag=1;
                    }
                }

            }
        }
        if(flag==0){
            //标记是否有第三级
            return CodeNum.TWO.getCode();
        }
        //第一层
        if(parentId.equals(NumCode.ZERO.getCode())){
            return CodeNum.ONE.getCode();
        }else {
            //第二层
            BmsMdBusinessCategory bms2=  bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryByGuId(bms.getParentId());
            String parentId2= bms2.getParentId();
            if(parentId2.equals(NumCode.ZERO.getCode())){
                return CodeNum.TWO.getCode();
            }else {
                //第三层
                return CodeNum.THREE.getCode();
            }
        }

    }
    public String getFileSize(long fileLength) {
    	DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileLength == 0) {
            return wrongSize;
        }
        if (fileLength < 1024) {
            fileSizeString = df.format((double) fileLength) + "B";
        } else if (fileLength < 1048576) {
            fileSizeString = df.format((double) fileLength / 1024) + "KB";
        } else if (fileLength < 1073741824) {
            fileSizeString = df.format((double) fileLength / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileLength / 1073741824) + "GB";
        }
        return fileSizeString;
    }
    
    /**
     * 新增模板下载
     * 
     * @param bmsKnowledgeTemplate 模板下载
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBmsKnowledgeTemplate(BmsKnowledgeTemplate bmsKnowledgeTemplate)
    {
        bmsKnowledgeTemplate.setCreateTime(DateUtils.getNowDate());
        bmsKnowledgeTemplate.setUpdateTime(DateUtils.getNowDate());
        String guid = UUID.randomUUID().toString();
        bmsKnowledgeTemplate.setGuid(guid);
        int res=bmsKnowledgeTemplateMapper.insertBmsKnowledgeTemplate(bmsKnowledgeTemplate);
        //典型案例guid
        //附件guid
        String contentGuid = bmsKnowledgeTemplate.getAttachmentId();
        BmsAttachment bmsAttachment= new BmsAttachment();
        bmsAttachment.setBizId(guid);
        bmsAttachment.setGuid(contentGuid);
        bmsAttachment.setCategory(AttachmentConstants.KNOWLEDGE_TEMPLATE);
        bmsAttachmentMapper.updateBmsAttachment(bmsAttachment);
        List<String> categorys = bmsKnowledgeTemplate.getBusinessCategoryGuids();
        //添加关联库的数据  业务类别的关联
        for (String bms:categorys) {
            BmsCategoryAssociated associated = new BmsCategoryAssociated();
            associated.setCategoryGuid(bms);
            associated.setParentGuid(guid);
            associated.setGuid(UUID.randomUUID().toString());
            associated.setFlag(CodeNum.TWO.getCode());
            bmsCategoryAssociatedMapper.insertBmsCategoryAssociated(associated);
        }
        return res;

    }

    /**
     * 修改模板下载
     * 
     * @param bmsKnowledgeTemplate 模板下载
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBmsKnowledgeTemplate(BmsKnowledgeTemplate bmsKnowledgeTemplate)
    {
        bmsKnowledgeTemplate.setUpdateTime(DateUtils.getNowDate());
        String contentGuid = bmsKnowledgeTemplate.getAttachmentId();
        String guid=bmsKnowledgeTemplate.getGuid();
        int res= bmsKnowledgeTemplateMapper.updateBmsKnowledgeTemplate(bmsKnowledgeTemplate);
        //先把上一次的附件去掉
        bmsAttachmentMapper.updateBmsAttachmentByGuid(guid, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
        BmsAttachment bmsAttachment= new BmsAttachment();
        bmsAttachment.setBizId(guid);
        bmsAttachment.setDelFlag(NumCode.ZERO.getCode());
        bmsAttachment.setGuid(contentGuid);
        bmsAttachment.setCategory(AttachmentConstants.KNOWLEDGE_TEMPLATE);
        bmsAttachmentMapper.updateBmsAttachment(bmsAttachment);
        //对业务类别进行修改先删除在重现添加
        bmsCategoryAssociatedMapper.deleteBmsCategoryAssociatedByParentId(guid);
        //添加
        List<String> categorys = bmsKnowledgeTemplate.getBusinessCategoryGuids();
        //添加关联库的数据  业务类别的关联
        for (String bms:categorys) {
            BmsCategoryAssociated associated = new BmsCategoryAssociated();
            associated.setCategoryGuid(bms);
            associated.setParentGuid(guid);
            associated.setGuid(UUID.randomUUID().toString());
            associated.setFlag(CodeNum.TWO.getCode());
            bmsCategoryAssociatedMapper.insertBmsCategoryAssociated(associated);
        }
        return res;

    }

    /**
     * 批量删除模板下载
     * 
     * @param guids 需要删除的模板下载ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBmsKnowledgeTemplateByGuids(String[] guids)
    {
        int res=bmsKnowledgeTemplateMapper.deleteBmsKnowledgeTemplateByGuids(guids);
        //删除所有的业务类别关联表数据
        bmsCategoryAssociatedMapper.deleteBmsCategoryAssociatedByParentIds(guids);
        //删除所有的附件数据。逻辑删除
        bmsAttachmentMapper.updateBmsAttachmentByBizId(guids, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
        return res;
    }

    /**
     * 删除模板下载信息
     * 
     * @param guid 模板下载ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBmsKnowledgeTemplateByGuid(String guid)
    {
        return bmsKnowledgeTemplateMapper.deleteBmsKnowledgeTemplateByGuid(guid);
    }
}
